﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace DiasPlanejamento
{
    public partial class MainWindow : INotifyPropertyChanged
    {
        public static readonly DependencyProperty InicioPeriodoProperty =
            DependencyProperty.Register("InicioPeriodo", typeof(DateTime), typeof(MainWindow),
                                        new PropertyMetadata(DateTime.Now));


        public static readonly DependencyProperty FimPeriodoProperty =
            DependencyProperty.Register("FimPeriodo", typeof(DateTime), typeof(MainWindow),
                                        new PropertyMetadata(DateTime.Now.AddDays(1)));

        public static readonly DependencyProperty AuthorsListProperty =
            DependencyProperty.Register("Horarios", typeof(List<Horario>), typeof(MainWindow),
                                        null);


        public MainWindow()
        {
            InitializeComponent();
            Carrega();
        }

        public DateTime InicioPeriodo
        {
            get { return (DateTime)GetValue(InicioPeriodoProperty); }
            set
            {
                SetValue(InicioPeriodoProperty, value);
                OnPropertyChanged();
            }
        }

        public DateTime FimPeriodo
        {
            get { return (DateTime)GetValue(FimPeriodoProperty); }
            set
            {
                SetValue(FimPeriodoProperty, value);
                OnPropertyChanged();
            }
        }


        public List<Horario> Horarios
        {
            get { return (List<Horario>)GetValue(AuthorsListProperty); }
            set
            {
                SetValue(AuthorsListProperty, value);
                OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            DataContext = this;
        }

        private void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            var handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var flowDoc = new FlowDocument();
            var table = new Table();
            flowDoc.Blocks.Add(table);
            table.Columns.Add(new TableColumn());
            table.RowGroups.Add(new TableRowGroup());

            var turma = ((Button)sender).Tag.ToString();

            var aulaCount = 1;

            var segCount = 0;
            var terCount = 0;
            var quaCount = 0;
            var quiCount = 0;
            var sexCount = 0;

            foreach (Horario horario in Horarios)
            {
                if (horario.Seg == turma)
                    segCount++;

                if (horario.Ter == turma)
                    terCount++;

                if (horario.Qua == turma)
                    quaCount++;

                if (horario.Qui == turma)
                    quiCount++;

                if (horario.Sex == turma)
                    sexCount++;
            }

            for (var data = InicioPeriodo; data <= FimPeriodo; data = data.AddDays(1))
                switch (data.Date.DayOfWeek)
                {
                    case DayOfWeek.Monday:
                        if (segCount > 0)
                            aulaCount = AddRow(table, aulaCount, segCount, data);
                        break;
                    case DayOfWeek.Tuesday:
                        if (terCount > 0)
                            aulaCount = AddRow(table, aulaCount, terCount, data);
                        break;
                    case DayOfWeek.Wednesday:
                        if (quaCount > 0)
                            aulaCount = AddRow(table, aulaCount, quaCount, data);
                        break;
                    case DayOfWeek.Thursday:
                        if (quiCount > 0)
                            aulaCount = AddRow(table, aulaCount, quiCount, data);
                        break;
                    case DayOfWeek.Friday:
                        if (sexCount > 0)
                            aulaCount = AddRow(table, aulaCount, sexCount, data);
                        break;
                }

            Saida.Document = flowDoc;
        }

        private static int AddRow(Table table, int aulaCount, int diaDaSemana, DateTime data)
        {
            var tableRow = new TableRow();
            table.RowGroups[0].Rows.Add(tableRow);

            var tableCell = new TableCell(new Paragraph(new Run(string.Format("Aula {3} ({0:dd/MM}) - {1} {2}", data.Date, diaDaSemana,
                                           diaDaSemana == 1 ? "período" : "períodos", aulaCount)))) { BorderBrush = Brushes.Black, BorderThickness = new Thickness(1) };

            tableRow.Cells.Add(tableCell);

            aulaCount++;
            return aulaCount;
        }

        private void Carrega()
        {
            var assembly = Assembly.GetExecutingAssembly();

            var result = "";
            using (var stream = assembly.GetManifestResourceStream("DiasPlanejamento.horarios.txt"))
                if (stream != null)
                    using (var reader = new StreamReader(stream))
                    {
                        result = reader.ReadToEnd();
                    }

            var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
            var serializer = new DataContractJsonSerializer(typeof(List<Horario>));
            Horarios = serializer.ReadObject(ms) as List<Horario>;
            ms.Close();
        }
    }
}